package _91Annotation.test;

import _91Annotation.bean.Dog;
import _91Annotation.bean.Person;
import _91Annotation.bean.PersonBase;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;

/**
 * @author user_xdd
 * @Date 2022-04-23 10:37
 * @description 测试深度克隆和浅度克隆，差别是浅度无法clone对象里的对象，需要再clone方法里去添加对象的clone方法
 * @return
 */

public class clone {
    private static final Logger LOGGER = Logger.getLogger(clone.class);
    //-------------------------------测试基本clone -------------------------------
/*
    @Test    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
*/

    public void cloneBase() {
        Dog dog = new Dog("旺财", 3);
        PersonBase person = new PersonBase("jack", "man", 20, dog);
        LOGGER.debug("    person:" + person);
        LOGGER.debug("    person.getDog():" + person.getDog());
        try {
            PersonBase otherPerson = (PersonBase) person.clone();//克隆不会调用构造函数
            LOGGER.debug("    otherPerson:" + otherPerson);
            LOGGER.debug("    otherPerson.getDog():" + otherPerson.getDog());

            LOGGER.debug("    person==otherPerson:" + (person == otherPerson));//克隆结果为属性相同的两个不同对象
            LOGGER.debug("    person.getDog()==otherPerson.getDog():" + (person.getDog() == otherPerson.getDog()));
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    //-------------------------------深度克隆 -------------------------------

/*
        //深度克隆 克隆Person的同时再克隆Dog
        Person  other = (Person) super.clone();
        Dog  otherDog = (Dog) this.dog.clone();
        other.setDog(otherDog);//将克隆Dog设置给克隆的Person
        return  other;
*/
    @Test
    public void cloneDep() {
        Dog dog = new Dog("旺财", 3);
        Person person = new Person("jack", "man", 20, dog);
        LOGGER.debug("    person:" + person);
        LOGGER.debug("    person.getDog():" + person.getDog());

        try {
            Person otherPerson = (Person) person.clone();//克隆不会调用构造函数
            LOGGER.debug("    otherPerson:" + otherPerson);
            LOGGER.debug("    otherPerson.getDog():" + otherPerson.getDog());

            LOGGER.debug("    person==otherPerson:" + (person == otherPerson));//克隆结果为属性相同的两个不同对象
            LOGGER.debug("    person.getDog()==otherPerson.getDog():" + (person.getDog() == otherPerson.getDog()));
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

    }
}
